/**
 * 
 */
package org.xelnaga.defiler.web.controller.category;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xelnaga.defiler.domain.CategoryModel;
import org.xelnaga.defiler.service.CategoryService;
/**
 * @author qijb
 *
 */
@Controller("generatedCategoryRestController")
@RequestMapping(value = "domain/rest/category")
public class CategoryRestController {
    @Autowired
    private CategoryService categoryService;

	/**
	 * 
	 */
	public CategoryRestController() {
		// TODO Auto-generated constructor stub
	}
	    
    @RequestMapping(value = "/children/{categoryId}")
    @ResponseBody
    public Object children(@PathVariable String categoryId, HttpServletRequest request, HttpServletResponse response) {
    	List<CategoryMessage> list = new ArrayList<CategoryMessage>();
    	if(StringUtils.equalsIgnoreCase(categoryId, "root")) {
    		List<CategoryModel> hostList = categoryService.getListByTop(null);
    		for(CategoryModel host : hostList) {
    			CategoryMessage hostMessage = new CategoryMessage(host);
    			list.add(hostMessage);
    			List<CategoryModel> childs = categoryService.getListByParentInode(host.getInode(), false);
    			if(null != childs && childs.size() > 0) {
	    			for(CategoryModel folder : childs) {
	    				CategoryMessage folderMessage = new CategoryMessage(folder);
	    				hostMessage.addChild(folderMessage);
	    			}
    			} else {
    				hostMessage.setChildren(new ArrayList<CategoryMessage>());
    			}
    		}
    		return list;
    	} else if(StringUtils.isNumeric(categoryId)) {//This is folder
    		CategoryMessage current = new CategoryMessage(categoryService.getByPrimaryKey(new Long(categoryId)));
    		List<CategoryModel> folders = categoryService.getListByParentInode(new Long(categoryId), false);
    		for(CategoryModel folder : folders) {
    			CategoryMessage message = new CategoryMessage(folder);
    			current.addChild(message);    				
    		}
    		if(null == current.getChildren()) {
    			current.setChildren(new ArrayList<CategoryMessage>());
    		}
    		return current;
    	} else {
    		return new CategoryMessage();
    	}
    }

}
